package com.samson.elasticsearch.controller;

import com.samson.elasticsearch.dao.ArticleDao;
import com.samson.elasticsearch.entity.ArticleEntity;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author samson
 * @version 1.0
 * @date 2019/7/4 11:31
 */
@RestController
@RequestMapping("/es")
public class ArticleController {

    @Autowired
    private ArticleDao articleDao;

    @Autowired
    private ElasticsearchTemplate est;

    /**
     * 创建索引
     */
    @RequestMapping("/createIndex")
    public void createIndex() {
        est.createIndex(ArticleEntity.class);
    }

    /**
     * 删除索引
     */
    @RequestMapping("/deleteIndex")
    public void deleteIndex() {
        est.deleteIndex(ArticleEntity.class);
    }

    //查询多个filed
    @RequestMapping("/query123456")
    public void testBooleanQuery(){
        NativeSearchQueryBuilder builder = new NativeSearchQueryBuilder();
        builder.withQuery(QueryBuilders.boolQuery()
                .must(QueryBuilders.matchQuery("title","豆腐"))
                .must(QueryBuilders.matchQuery("content","豆腐"))
        );
        Page<ArticleEntity> page = this.articleDao.search(builder.build());
        for(ArticleEntity entity :page){
            System.out.println(entity);
        }
    }
}
